package com.yl.immodule.v;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.camera.base.inerface.WebModelFactory;
import com.camera.base.util.DefaultWebModelFactory;
import com.camera.base.v.BaseActivity;
import com.camera.base.wbmodels.WebModel;
import com.camera.routemodule.RouterPath;
import com.google.android.material.textfield.TextInputEditText;
import com.google.gson.Gson;
import com.hm.poc.http.HttpSenderManager;
import com.unionbroad.greendao.MessageDialogue;
import com.unionbroad.greendao.User;
import com.yl.immodule.APP;
import com.yl.immodule.IMApplocation;
import com.yl.immodule.R;
import com.yl.immodule.databinding.ActivityLoginBinding;
import com.yl.immodule.dialog.CustomDialog;
import com.yl.immodule.eventbus.LoginOutSideEvent;
import com.yl.immodule.permission.RxPermissions;
import com.android.yl.ylicpsdk.ICPRtcManager;
import com.android.yl.ylicpsdk.ICPRtcEventHandler;
import com.hm.poc.utils.ToastService;
import com.yl.immodule.v.models.LoginViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.disposables.Disposable;

@AndroidEntryPoint
@Route(path = RouterPath.path.login_activity)
public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginViewModel> {
    private final static String TAG = LoginActivity.class.getSimpleName();
    @NonNull
    @Override
    protected Class<LoginViewModel> getViewModelClass() {
        return LoginViewModel.class;
    }
    private EditText mAccountView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;
    private CustomDialog mCustomDialog;

    SharedPreferences mSharedPreferences;
    private RxPermissions rxPermissions = new RxPermissions(this);
    Disposable checkPerDisposable;
    private WebModelFactory mWebModelFactory  = new DefaultWebModelFactory();
    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public int getStatusBarColor() {
        return R.color.title_background_color;
    }

    @Override
    public void loadData() {

    }

    @Override
    public void initView() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSharedPreferences = getSharedPreferences("poc-im", Context.MODE_PRIVATE);
        EventBus.getDefault().register(this);
        mAccountView = (TextInputEditText) findViewById(R.id.email);
        mPasswordView = (TextInputEditText) findViewById(R.id.password);
        Button btnSet = (Button) findViewById(R.id.btn_activity_login_set);
        btnSet.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCustomDialog == null || !mCustomDialog.isShowing()) {
                    mCustomDialog = new CustomDialog(LoginActivity.this);
                    mCustomDialog.show();
                }
            }
        });
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        final Button signInButton = (Button) findViewById(R.id.email_sign_in_button);
        signInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);

//        mAccountView.setText(mSharedPreferences.getString("account", "20202010"));
//        mPasswordView.setText(mSharedPreferences.getString("password", "13579"));
        mAccountView.setText(mSharedPreferences.getString("account", "21041007"));
        mPasswordView.setText(mSharedPreferences.getString("password", "13579"));

        if (ICPRtcManager.getsInstance().hasServiceConnected()) {
//            LoginActivity.this.startActivity(new Intent(LoginActivity.this, HomeActivity.class));
            LoginActivity.this.finish();
        } else {
            signInButton.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //signInButton.performClick();c
                }
            }, 1000);
        }
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        //根据唯一码获取账号信息
        findViewById(R.id.get_account_button).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
//                showProgress(true);

                ICPRtcManager.getsInstance().addEventHandler(icpRtcEventHandler);
                ICPRtcManager.getsInstance().login("123456");
            }
        });
        checkPer();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        moveTaskToBack(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void checkPer() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
            requestAndroid11SDCardPermission();
            Toast.makeText(getApplicationContext(), "授权外置sd权限后重启app", Toast.LENGTH_SHORT).show();
            return;
        }

        checkPerDisposable = rxPermissions.requestEachCombined(
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.READ_PHONE_STATE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        APP.updatePermission(true);
                        requestSettingCanDrawOverlays();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        String tip = "缺少权限: " + permission.name;
                        Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_LONG).show();
                    } else {
                        String tip = "缺少权限: " + permission.name;
                        Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_LONG).show();
                    }
                });
    }

    private void requestAndroid11SDCardPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
                startActivityForResult(intent, 2296);
            } catch (Exception e) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivityForResult(intent, 2296);
            }
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginOutSideEvent event){
        if (event.account == null || event.password == null || event.account.equals("") || event.password.equals("")){
            APP.toastService.showToast("参数错误");
            return;
        }
        //外部登录
        mAccountView.setText(event.account);
        mPasswordView.setText(event.password);
        attemptLogin();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideLoadingDialog();
        EventBus.getDefault().unregister(this);
        if (checkPerDisposable != null) {
            checkPerDisposable.dispose();
        }
    }

    private void requestSettingCanDrawOverlays() {
        int sdkInt = Build.VERSION.SDK_INT;
        if (sdkInt >= 26 && !checkFloatPermission(this)) {//8.0以上
            Toast.makeText(LoginActivity.this, "hint_open_manage_windhow", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivityForResult(intent, 109);
        } else if (sdkInt >= 23 && !checkFloatPermission(this)) {//6.0-8.0
            Toast.makeText(LoginActivity.this, "hint_open_manage_windhow", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 109);
        } else {//4.4-6.0一下

        }
    }

    public static boolean checkFloatPermission(Context context) {
        if (Build.VERSION.SDK_INT < 19)
            return true;
        if (Build.VERSION.SDK_INT < 23) {
            try {
                Class cls = Class.forName("android.content.Context");
                Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                declaredField.setAccessible(true);
                Object obj = declaredField.get(cls);
                if (!(obj instanceof String)) {
                    return false;
                }
                String str2 = (String) obj;
                obj = cls.getMethod("getSystemService", String.class).invoke(context, str2);
                cls = Class.forName("android.app.AppOpsManager");
                Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                declaredField2.setAccessible(true);
                Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName());
                return result == declaredField2.getInt(cls);
            } catch (Exception e) {
                return false;
            }
        } else {
            if (Build.VERSION.SDK_INT >= 26) {
                AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                if (appOpsMgr == null)
                    return false;
                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), context
                        .getPackageName());
                return Settings.canDrawOverlays(context) || mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED;
            } else {
                return Settings.canDrawOverlays(context);
            }
        }
    }


    private void attemptLogin() {
        // Reset errors.
        mAccountView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mAccountView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mAccountView.setError(getString(R.string.error_field_required));
            focusView = mAccountView;
            cancel = true;
        } else if (!isNumberValid(email)) {
            mAccountView.setError(getString(R.string.error_invalid_email));
            focusView = mAccountView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showLoadingDialog("登录...");
            //登录
            ICPRtcManager.getsInstance().addEventHandler(icpRtcEventHandler);
            ICPRtcManager.getsInstance().login(email, password);

            mSharedPreferences.edit().putString("account", email).commit();
            mSharedPreferences.edit().putString("password", password).commit();
        }
    }

    //登录时相关的回调，该过程可能需要几秒，可根据不同状态显示相应的UI
    ICPRtcEventHandler icpRtcEventHandler = new ICPRtcEventHandler() {

        @Override
        public void onLoginStepProgress(int progress, String msg) {
            if (progress == LoginProgress.PRO_LOGIN_SUCCESS) {
                ICPRtcManager.getsInstance().removeEventHandler(icpRtcEventHandler);
//                LoginActivity.this.startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                Intent intentSuc = new Intent("login_success");
                intentSuc.addFlags(0x01000000);

//                intentSuc.setPackage("com.icp.demo");
                LoginActivity.this.sendBroadcast(intentSuc);
                hideLoadingDialog();
                LoginActivity.this.finish();
            } else if (progress == LoginProgress.PRO_BINDING_ACCOUNT_FAILED) {
                Toast.makeText(LoginActivity.this, "Login failed " + msg, Toast.LENGTH_SHORT).show();
            } else if (progress == LoginProgress.PRO_BINDING_ACCOUNT_NOT_EXIST) {
                Toast.makeText(LoginActivity.this, "Login failed " + msg, Toast.LENGTH_SHORT).show();
            } else if (progress == LoginProgress.PRO_BINDING_ACCOUNT_NOT_ACTIVE) {
                Toast.makeText(LoginActivity.this, "Login failed " + msg, Toast.LENGTH_SHORT).show();
            } else if (progress == LoginProgress.PRO_LOGIN_FAILED) {
                hideLoadingDialog();
                Toast.makeText(LoginActivity.this, "Login failed " + msg, Toast.LENGTH_SHORT).show();
            }
            if (progress != LoginProgress.PRO_LOGIN_FAILED){
                Log.e(TAG, "onLoginStepProgress: " );
                showLoadingDialog(msg);
            }

//            ((TextView) findViewById(R.id.tips)).setText(msg);
        }
    };

    private boolean isNumberValid(String input) {
        try {
            Long.valueOf(input);
            return true;
        } catch (Exception e) {

        }
        return false;
    }

    private boolean isPasswordValid(String password) {
        return password.length() > 4;
    }



//    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
//    private void showProgress(final boolean show) {
//        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
//        // for very easy animations. If available, use these APIs to fade-in
//        // the progress spinner.
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
//            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
//
//            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
//                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//                }
//            });
//
//            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
//            mProgressView.animate().setDuration(shortAnimTime).alpha(
//                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
//                }
//            });
//        } else {
//            // The ViewPropertyAnimator APIs are not available, so simply show
//            // and hide the relevant UI components.
//            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
//            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//        }
//
//        findViewById(R.id.tips).setVisibility(show ? View.VISIBLE : View.GONE);
//    }


}